package com.yyds.tensordemo;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import be.tarsos.dsp.io.android.AndroidFFMPEGLocator;


public class MainActivity extends AppCompatActivity {

    final public static int FILE_SELECT_CODE = 1;
    String audioPath;
    //请求码
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_MEDIA_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new AndroidFFMPEGLocator(this);

        findViewById(R.id.tv).setOnClickListener(v -> {
            tfliteModelPath = getCacheDir().getPath() + "/audionew.tflite";
            Log.e("TAG", "tfliteModelPath:" + tfliteModelPath);
            copyAssetsToSD("audio.tflite", tfliteModelPath);
            pickRecord();
        });


    }

    public void pickRecord() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                load(MainActivity.this);
            }
        }).start();

    }

    private void copyAssetsToSD(String assetName, String pathToFile) {
        File file = new File(pathToFile);
        if (file.exists() && file.length() > 0) {
            return;
        }
        AssetManager assetManager = getAssets();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(assetName);
            File outFile = new File(pathToFile);
            out = new FileOutputStream(outFile);

            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    String tfliteModelPath; /*= "file:///android_asset/audio.tflite";*/

    void load(Context context) {

        try {
            // 初始化音频预处理器
            AudioPreprocessor audioPreprocessor = new AudioPreprocessor(audioPath);

            // 提取音频特征和生成掩码
            float[][][] features = audioPreprocessor.extractFeatures(context, 100, 13);
            if (features == null) {
                return;
            }
            float[][] mask = audioPreprocessor.generateMask(features);


            // 创建推理助手并进行推理
            InferenceHelper inferenceHelper = new InferenceHelper();
            inferenceHelper.loadModel(tfliteModelPath);

            // 推理处理
            int[] predictedClasses = inferenceHelper.runInference(features, mask);
            if (predictedClasses == null) {
                return;
            }
            // 输出预测结果
            for (int predictedClass : predictedClasses) {
                Log.d("TAG", "Predicted class: " + predictedClass);
            }

            // 显示成功消息
//            Toast.makeText(this, "Inference completed!", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
//            Toast.makeText(this, "Error occurred during processing.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    Log.e("uri", uri.toString());
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
                    int actual_image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    audioPath = cursor.getString(actual_image_column_index);
                    Log.e("TAG)URI", audioPath);

                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
                tfliteModelPath = getCacheDir().getPath() + "/audionew.tflite";
                Log.e("TAG", "tfliteModelPath:" + tfliteModelPath);
                copyAssetsToSD("audio.tflite", tfliteModelPath);
                pickRecord();
            }
        }
    }
}
